package org.xhy.security.handler;

import com.alibaba.fastjson.JSON;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        //设置响应字符集
        httpServletResponse.setContentType("application/json;charset=utf-8");

        e.printStackTrace();

        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("success",false);
        hashMap.put("message","登录失败");

        String jsonString = JSON.toJSONString(hashMap);

        httpServletResponse.getWriter().print(jsonString);
    }
}
